// pages/index/index.js
Page({
  data: {
    display: '',
    result: '',
    error: '',
    memory: 0,
    history: [],
    showHistory: false,
    conversionMode: 'none',
    conversionUnit: 'in2cm'
  },

  onLoad: function() {
    // 页面加载时执行
  },

  // 检测错误输入
  validateInput: function(input) {
    const cleanInput = input.replace(/\s/g, '');
    const validChars = /^[0-9+\-*/()\.]+$/;
    return validChars.test(cleanInput);
  },

  // 格式化字符串，处理连续的正负号
  formatExpression: function(s) {
    let formatted = s.replace(/,/g, '');
    formatted = formatted.replace(/\+\+/g, '+');
    formatted = formatted.replace(/\+-/g, '-');
    formatted = formatted.replace(/-\+/g, '-');
    formatted = formatted.replace(/--/g, '+');
    return formatted;
  },

  // 计算表达式（不包含括号）
  calculateExpression: function(expression) {
    let s = expression;

    // 处理乘除运算
    while (/[*/]/.test(s)) {
      s = this.formatExpression(s);
      const match = s.match(/[*/]/);
      if (!match) break;

      const operator = match[0];
      const operatorIndex = s.indexOf(operator);
      
      // 找到运算符前后的数字
      const beforeOperator = s.substring(0, operatorIndex);
      const afterOperator = s.substring(operatorIndex + 1);
      
      const firstMatch = beforeOperator.match(/[\d.]+$/);
      const secondMatch = afterOperator.match(/^[\d.]+/);
      
      if (!firstMatch || !secondMatch) break;

      const first = firstMatch[0];
      const second = secondMatch[0];
      
      const fir = first.includes('.') ? parseFloat(first) : parseInt(first);
      const sec = second.includes('.') ? parseFloat(second) : parseInt(second);
      
      let result;
      if (operator === '*') {
        result = fir * sec;
      } else if (operator === '/') {
        if (sec === 0) {
          throw new Error('除数不能为零');
        }
        result = fir / sec;
      } else {
        break;
      }
      
      s = s.replace(`${first}${operator}${second}`, result.toString());
    }

    // 处理加减运算
    while (/[+-]/.test(s)) {
      s = this.formatExpression(s);
      const match = s.match(/[+-]/);
      if (!match) break;

      const operator = match[0];
      const operatorIndex = s.indexOf(operator);
      
      // 跳过开头的负号
      if (operatorIndex === 0) {
        const nextMatch = s.substring(1).match(/[+-]/);
        if (!nextMatch) break;
        const nextIndex = s.indexOf(nextMatch[0], 1);
        const beforeOperator = s.substring(0, nextIndex);
        const afterOperator = s.substring(nextIndex + 1);
        
        const firstMatch = beforeOperator.match(/[\d.]+$/);
        const secondMatch = afterOperator.match(/^[\d.]+/);
        
        if (!firstMatch || !secondMatch) break;

        const first = firstMatch[0];
        const second = secondMatch[0];
        
        const fir = first.includes('.') ? parseFloat(first) : parseInt(first);
        const sec = second.includes('.') ? parseFloat(second) : parseInt(second);
        
        let result;
        if (nextMatch[0] === '+') {
          result = fir + sec;
        } else {
          result = fir - sec;
        }
        
        s = s.replace(`${first}${nextMatch[0]}${second}`, result.toString());
      } else {
        const beforeOperator = s.substring(0, operatorIndex);
        const afterOperator = s.substring(operatorIndex + 1);
        
        const firstMatch = beforeOperator.match(/[\d.]+$/);
        const secondMatch = afterOperator.match(/^[\d.]+/);
        
        if (!firstMatch || !secondMatch) break;

        const first = firstMatch[0];
        const second = secondMatch[0];
        
        const fir = first.includes('.') ? parseFloat(first) : parseInt(first);
        const sec = second.includes('.') ? parseFloat(second) : parseInt(second);
        
        let result;
        if (operator === '+') {
          result = fir + sec;
        } else {
          result = fir - sec;
        }
        
        s = s.replace(`${first}${operator}${second}`, result.toString());
      }
    }

    return s;
  },

  // 处理括号
  processParentheses: function(expression) {
    let s = expression;
    
    while (/\([^()]+\)/.test(s)) {
      const match = s.match(/\([^()]+\)/);
      if (!match) break;
      
      const parenthesesContent = match[0];
      const contentWithoutParentheses = parenthesesContent.slice(1, -1);
      
      const result = this.calculateExpression(contentWithoutParentheses);
      s = s.replace(parenthesesContent, result);
    }
    
    return this.calculateExpression(s);
  },

  // 单位换算函数
  convertUnit: function(value, unit) {
    switch (unit) {
      case 'in2cm': // 英寸到厘米
        return value * 2.54;
      case 'ft2m': // 英尺到米
        return value * 0.3048;
      case 'cm2in': // 厘米到英寸
        return value / 2.54;
      case 'm2ft': // 米到英尺
        return value / 0.3048;
      default:
        return value;
    }
  },

  // 处理单位换算
  handleConversion: function() {
    try {
      const value = parseFloat(this.data.display);
      if (isNaN(value)) {
        this.setData({
          error: '请输入有效数字'
        });
        return;
      }

      const result = this.convertUnit(value, this.data.conversionUnit);
      const unitLabel = this.getUnitLabel();
      
      this.setData({
        result: `${result.toFixed(4)}`,
        display: `${result.toFixed(4)}`,
        history: [
          ...this.data.history,
          { 
            expression: `${value} ${unitLabel.from}`, 
            result: `${result.toFixed(4)} ${unitLabel.to}` 
          }
        ]
      });
    } catch (error) {
      this.setData({
        error: error instanceof Error ? error.message : '换算错误'
      });
    }
  },

  // 获取单位标签
  getUnitLabel: function() {
    switch (this.data.conversionUnit) {
      case 'in2cm':
        return { from: '英寸', to: '厘米' };
      case 'ft2m':
        return { from: '英尺', to: '米' };
      case 'cm2in':
        return { from: '厘米', to: '英寸' };
      case 'm2ft':
        return { from: '米', to: '英尺' };
      default:
        return { from: '', to: '' };
    }
  },

  // 处理内存操作
  handleMemory: function(operation) {
    switch (operation) {
      case 'MC': // Memory Clear
        this.setData({ memory: 0 });
        break;
      case 'MR': // Memory Recall
        this.setData({ display: this.data.memory.toString() });
        break;
      case 'M+': // Memory Add
        try {
          const value = parseFloat(this.data.display || '0');
          this.setData({ memory: this.data.memory + value });
        } catch (error) {
          this.setData({ error: '无效的数字' });
        }
        break;
      case 'M-': // Memory Subtract
        try {
          const value = parseFloat(this.data.display || '0');
          this.setData({ memory: this.data.memory - value });
        } catch (error) {
          this.setData({ error: '无效的数字' });
        }
        break;
    }
  },

  // 处理按钮点击
  handleButtonClick: function(e) {
    const value = e.currentTarget.dataset.value;
    
    this.setData({ error: '' });

    if (value === '=') {
      try {
        if (!this.validateInput(this.data.display)) {
          this.setData({ error: '输入包含无效字符' });
          return;
        }
        
        const result = this.processParentheses(this.data.display);
        this.setData({
          result: result,
          display: result,
          history: [
            ...this.data.history,
            { expression: this.data.display, result: result }
          ]
        });
      } catch (error) {
        this.setData({
          error: error instanceof Error ? error.message : '计算错误'
        });
      }
    } else if (value === 'C') {
      this.setData({
        display: '',
        result: '',
        error: ''
      });
    } else if (value === '⌫') {
      this.setData({
        display: this.data.display.slice(0, -1)
      });
    } else if (['MC', 'MR', 'M+', 'M-'].includes(value)) {
      this.handleMemory(value);
    } else if (value === 'CONV') {
      if (this.data.conversionMode === 'none') {
        this.setData({ conversionMode: 'length' });
      } else {
        this.handleConversion();
      }
    } else if (['in2cm', 'ft2m', 'cm2in', 'm2ft'].includes(value)) {
      this.setData({ conversionUnit: value });
    } else if (value === 'HIST') {
      this.setData({ showHistory: !this.data.showHistory });
    } else {
      this.setData({ display: this.data.display + value });
    }
  },

  // 使用历史记录项
  useHistoryItem: function(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.history[index];
    
    this.setData({
      display: item.result,
      showHistory: false
    });
  },

  // 清除历史记录
  clearHistory: function() {
    this.setData({ history: [] });
  },

  // 返回标准计算器模式
  returnToCalculator: function() {
    this.setData({ conversionMode: 'none' });
  }
});